package org.game.module.datingbo.handler;

import com.sojoys.artifact.tools.ToolError;
import org.cfg.DatingCfg;
import org.error.GameErrorCode;
import org.game.constant.DatingTypeConstant;
import org.game.db.bean.CurrentScriptRecord;
import org.game.db.bean.Dating;
import org.game.db.bean.Player;
import org.game.db.bean.Role;
import org.game.db.cache.RoleCache;
import org.game.log.LogDating;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.DatingDsp;
import org.game.manager.DatingManager;
import org.game.module.datingbo.DatingBO;
import org.game.module.datingbo.DatingType;
import org.game.msgBuilder.DatingMsgBuilder;
import org.game.protobuf.c2s.C2SDatingMsg;
import org.game.util.ProtoUnit;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 触发约会
 * Created by fxf on 2017/11/20.
 */
@DatingType(DatingTypeConstant.DATING_TYPE_TRIGGER)
public class TriggerDatingHandler extends AbstractDatingHandler {
    @Override
    public byte[] getScript(Player player, C2SDatingMsg.GetScriptMsg msg) {
        int scriptId = msg.getScriptId();
        int roleId = msg.getRoleId();
        Role role = RoleCache.me().getByCidPlayerId(roleId,player.getId());
        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR,"触发约会，无效的roleId",role == null);
        ToolError.isAndTrue(GameErrorCode.NOT_TRIGGER_SCRIPT,"触发约会，无效的剧本id，改剧本未触发",!role.getTriggerDating().contains(scriptId));
        Dating dating = DatingManager.getDating(player);
        ToolError.isAndTrue(GameErrorCode.COMPLETED_DATING,"触发约会，已经完成的约会",dating.getScriptIdList().contains(scriptId));
        Map<Integer, List<Integer>> branchNodes = getScriptBranchNode(player, scriptId,msg);
        int startNodeId = getStartNodeId(scriptId);
        createCurrentScriptRecord(player, scriptId, branchNodes, startNodeId, Arrays.asList(roleId));

        LogDating.me().log(player.getId(),DatingTypeConstant.DATING_TYPE_TRIGGER,scriptId,player.getPlayerProxy().getCurrentRole().getRoleProxy().getConfig().getId(), LogDsp.newBuilder(DatingDsp.GET_SCRIPT));
        player.getPlayerProxy().sendMsg(DatingBO.sendEveryDayScript,DatingMsgBuilder.getDatingScriptMsg(scriptId,branchNodes));
        return new byte[0];

    }

    @Override
    protected void endDatingRecord(Player player, Dating dating, DatingCfg cfg,int roleCid,CurrentScriptRecord record) {
        super.endDatingRecord(player,dating,cfg,roleCid,record);
        Role role = RoleCache.me().getByCidPlayerId(roleCid,player.getId());
        role.update();
        player.getPlayerProxy().sendMsg(DatingBO.updateTriggerDating, DatingMsgBuilder.createUpdateTriggerDatingMsg(role));
    }
}
